const db = require('../db/Model/Model')
const uuid = require('node-uuid')
const Token = require('./token')
const jwtKey = '_id_username_???_<<<>LLL'
const dayjs = require('dayjs')


// 注册接口
function register(req, res) {
    const user = {
        _id: uuid(),
        username: req.body.username,
        password: req.body.password
    }
    console.log(user)
    db.userModel.find({ username: user.username }, (err, docs) => {
        if (err) {
            res.send({
                code: 500,
                msg: "数据库错误"
            })
        } else {
            if (docs.length !== 0) {
                res.send({
                    msg: "用户名已存在",
                    code: 200
                })
            } else {
                db.userModel.create(user, err => {
                    if (err) {
                        res.send({
                            msg: '数据库连接错误',
                            data: err
                        })
                    } else {
                        res.send({
                            msg: '注册成功',
                        })
                    }
                })
            }
        }
    })
}

// 登陆接口
function login(req, res) {
    console.log(req.body)
    const { username, password } = req.body
    db.userModel.findOne({ username, password }, (err, docs) => {
        if (err) {
            res.send({
                code: 500,
                msg: "数据库出错",
                data: {
                    token: ""
                }
            })
        } else {
            if (docs === null) {
                res.send({
                    msg: "该用户不存在，请注册后登陆",
                    code: 200,
                    data: {
                        token: ""
                    }
                })
                return
            }
            if (docs.length !== 0 && docs.username === username && docs.password === password) {
                const _id = docs._id
                const token = Token.encryptionToken(_id, jwtKey)
                db.userModel.updateOne({ username, password }, { _id, username, password, token }, (err, result) => {
                    if (err) {
                        return res.send({
                            msg: err.message,
                            code: 500
                        })
                    } else {
                        return res.send({
                            code: 200,
                            msg: "登陆成功",
                            data: {
                                token
                            }
                        })
                    }
                })
            } else {
                res.send({
                    msg: "该用户不存在，请注册后登陆",
                    code: 200,
                    data: {
                        token: ""
                    }
                })
            }
        }
    })
}

// 获取请求中token的id
function checkToken(req, res) {
    const tokenKey = Token.decryptToken(req.headers.token, jwtKey)
    return tokenKey._id
}

// 添加todo
function addTodo(req, res) {
    const userId = checkToken(req, res)
    if (userId === 'tokenKey is error') {
        return res.send({
            code: 200,
            msg: "用户未登陆，请登陆后操作！",
        })
    }
    else {
        //生成todoId
        const todoId = uuid()
        // 生成创建时间
        const createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
        const { title, done } = req.body

        // 查询数据库内是否有该用户的集合
        db.todoModel.findOne({ _id: userId }, (err, docs) => {
            // 已有用户数据，直接添加
            if (docs) {
                push(req, res, { _id: userId }, { _id: todoId, title, done, createTime })
                return
            }
            // 创建用户ID数据，再添加
            else {
                db.todoModel.create({ _id: userId, todos: [] }, (err, result) => {
                    if (err) {
                        res.send({
                            msg: "保存失败",
                            data: ""
                        })
                    } else {
                        push(req, res, { _id: userId }, { _id: todoId, title, done, createTime })
                    }
                })
            }
        })
    }
}

// 查询todo
function searchTodo(req, res) {
    const userId = checkToken(req, res)
    if (userId === 'tokenKey is error') {
        return res.send({
            code: 200,
            msg: "用户未登陆，请登陆后操作！",
        })
    }

    db.todoModel.findOne({ _id: userId }, (err, docs) => {
        if (err) {
            res.send({
                msg: "查询失败",
            })
        }
        else if (docs === null) {
            res.send({
                msg: "查询成功",
                data: ""
            })
        }
        else {
            res.send({
                msg: "查询成功",
                data: docs.todos
            })
        }
    })
}

// 修改todo
function updateTodo(req, res) {
    const userId = checkToken(req, res)
    if (userId === 'tokenKey is error') {
        return res.send({
            code: 200,
            msg: "用户未登陆，请登陆后操作！",
        })
    }
    const { _id, title } = req.body

    // 调用封装好的数据方法
    update(
        req,
        res,
        _id,
        { "todos.$.title": title }
    )
}

// 修改done
function changDone(req, res) {
    const userId = checkToken(req, res)
    if (userId === 'tokenKey is error') {
        return res.send({
            code: 200,
            msg: "用户未登陆，请登陆后操作！",
        })
    }

    const { _id, done } = req.body
    update(req, res, _id, { "todos.$.done": done })
}

// 获取已完成的todo和长度
function doneNow(req, res) {
    const userId = checkToken(req, res)
    if (userId === 'tokenKey is error') {
        return res.send({
            code: 200,
            msg: "用户未登陆，请登陆后操作！",
        })
    }
    db.todoModel.findOne({ _id: userId }, (err, docs) => {
        if (err) {
            res.send({
                msg: err.message
            })

        }
        else if (docs === null) {
            console.log(docs)
            res.send({
                msg: "数组为空",
                data: ""
            })
        }
        else {
            const todos = []
            docs.todos.forEach(item => {
                if (item.done) {
                    todos.push(item)
                }
            });
            res.send({
                msg: '获取成功',
                data: {
                    doneTodos: todos,
                    doneLength: todos.length
                }
            })
        }
    })
}


// 删除todo
function deleteTodo(req, res) {
    const userId = checkToken(req, res)
    if (userId === 'tokenKey is error') {
        return res.send({
            code: 200,
            msg: "用户未登陆，请登陆后操作！",
        })
    }

    const _id = req.body._id
    // 调用封装好的删除方法
    remove(req, res, userId, _id)
}


// 往数组添加数据  query查询条件，todo是要添加的文档
function push(req, res, query, todo) {
    db.todoModel.updateOne(query, {
        "$push": {
            todos: todo
        }
    }, (err, result) => {
        if (err) {
            res.send({
                msg: err.message,
                code: 500
            })
        } else {
            res.send({
                msg: "保存成功",
                code: 200
            })
        }
    })
}


// 修改数组的指定数据  _id是要修改的todoid, updataObj是要修改的属性和属性值对象
function update(req, res, _id, updateObj) {
    db.todoModel.updateOne(
        { "todos._id": _id },
        {
            $set: updateObj
        },
        (err, result) => {
            if (err) {
                res.send({
                    msg: err.message,
                    code: 500
                })
            } else {
                res.send({
                    msg: "修改成功",
                    code: 200
                })
            }
        }
    )
}


// 删除数据  userId是用户id，_id是todoid
function remove(req, res, userId, _id) {
    db.todoModel.updateOne({ _id: userId },
        {
            $pull: {
                "todos": {
                    _id,
                }
            }
        },
        (err, result) => {
            if (err) {
                res.send({
                    code: 500,
                    msg: err.message
                })
            } else {
                res.send({
                    code: 200,
                    msg: "删除成功"
                })
            }
        }
    )
}

module.exports = {
    register,
    login,
    // checkToken,
    addTodo,
    searchTodo,
    updateTodo,
    deleteTodo,
    changDone,
    doneNow,
}